<template>
    <div class="editor">
        <!-- <nav-header  v-show="show"></nav-header> -->
        <div class="title">发布文章</div>
        <el-form ref="form" :model="form" :rules="rules" label-width="6rem">
            <!-- 标题 -->
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" maxlength="20"></el-input>
            </el-form-item>
            <!-- 作者 -->
            <!-- <el-form-item label="作者" prop="author">
            </el-form-item> -->
            <!-- 所属模块 -->
            <el-form-item label="所属类型" prop="type">
                <el-select v-model="form.type">
                    <el-option :label="item.name" :value="item.tabId" v-for="(item,editor) in typeList" :key="editor">{{item.name}}</el-option>
                </el-select>
            </el-form-item>
            <!-- 标签 -->
            <el-form-item label="文章标签" prop="tags">
                <el-checkbox-group v-model="checkList" :max="3">
                    <el-checkbox :label="parseInt(item.tagId)" v-for="(item,editor) in tagsList" :key="editor">
                        {{item.name}}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <!-- 摘要-->
            <el-form-item label="摘要" prop="summary">
                <el-input v-model="form.summary" ></el-input>
            </el-form-item>
            <!-- 内容 -->
            <el-form-item label="内容" prop="content">
                <div class=" ql-container ql-snow">
                    <div class="ql-editor">
                        <quill-editor
                        v-model="form.content"
                        :style="{
                            height: '450px',
                            border: borderColor,
                        }"
                        class="quill"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @change="onEditorChange($event)"
                        ></quill-editor>
                    </div>
                </div>

            </el-form-item>
            <!-- 上传附件 -->
            <el-form-item label="上传附件" prop="file" class="uploadfile">
                <el-upload
                class="upload-demo"
                action="https://www.seeumt.club/intelligence/upload/"
                :on-success="handleFileSuccess"
                :on-remove="handleFileRemove"
                :limit="10"
                :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <!-- <div slot="tip" class="el-upload__tip">最多上传十个文件~</div> -->
                </el-upload>
            </el-form-item>
            <!-- 上传文章封面 -->
            <el-form-item label="上传封面" prop="imageUrl" class="uploadimg">
                <el-upload
                v-model="form.url"
                class="avatar-uploader"
                action="https://www.seeumt.club/intelligence/upload/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                    <img v-if="url" :src="url" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item class="btn">
                <el-button type="primary" @click="handleSee">预览效果 </el-button>
                <el-button type="primary" @click="postArticle">上传</el-button>
            </el-form-item>
        </el-form>
        <el-dialog title="预览效果" :visible.sync="dialogTableVisible" class=" ql-container ql-snow">
            <div style="min-height: 60vh;"  class="ql-editor">
                <h1 class="news-title">{{ form.title }}</h1>
                <div>作者：{{form.author}}</div>
                <div class="news-content" v-html="form.content"></div>
                <div class="addfile">
                    附件（点击预览）
                    <div class="filename" v-for="(item,editor) in fileList" :key="editor">{{item.name}}</div>
                </div>

            </div>
        </el-dialog>
        <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
            <span>发布成功！</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import NavHeader from './../components/NavHeader'

import { quillEditor } from "vue-quill-editor";
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
    export default {
        name: "editor",
        components: {
            quillEditor,
            // NavHeader
        },
        data() {
            return {
                show : true,
                borderColor: "#dcdfe6",
                dialogTableVisible: false,
                form: {
                    title: "",
                    author: "",
                    type: "",
                    summary: "",
                    content: "",
                    url: ""
                },
                editorOption: {
                    placeholder: "",
                    modules: {
                    toolbar: [
                        [{ header: [1, 2, 3, 4, 5, 6, false] }],
                        [{ size: ["small", false, "large", "huge"] }],
                        ["bold", "italic", "underline", "strike"],
                        ["blockquote", "code-block"],
                        [{ list: "ordered" }, { list: "bullet" }],
                        [{ script: "sub" }, { script: "super" }],
                        [{ indent: "-1" }, { indent: "+1" }],
                        [{ direction: "rtl" }],
                        [{ color: [] }, { background: [] }],
                        [{ align: [] }],
                        ["clean"],
                        ["link", "image", "video"],
                    ],
                    },
                },
                rules: {
                    title: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "blur",
                    },
                    ],
                    author: [
                    {
                        required: true,
                        message: "请输入作者",
                        trigger: "blur",
                    },
                    ],
                    type: [
                    {
                        required: true,
                        message: "请选择文章类型",
                        trigger: "change",
                    },
                    ],
                    summary: [
                    {
                        required: true,
                        message: "请输入摘要",
                        trigger: "blur",
                    },
                    ],
                    content: [
                    {
                        required: true,
                        message: "请输入内容",
                        trigger: "blur",
                    },
                    ],
                    imageUrl: [
                    {
                        required: true,
                        message: "请上传文章封面",
                        trigger: "blur",
                    },
                    ],
                },
                files:[],
                remo:[],
                fileList: [],
                checkList: [],
                tagsList:[],
                typeList:[],
                url: '',
                uname:"",
                centerDialogVisible: false
            }
        },
        mounted() {
            //可用于设置自适应屏幕，根据获得的可视宽度（兼容性）判断是否显示
            let w = document.documentElement.offsetWidth || document.body.offsetWidth;
            if(w < 1000){
                this.show = false;
            }
            this.getTags();
            this.getTabs();
        },
        created(){
            var uname = localStorage.getItem('u_name');
            this.uname = uname
            this.form.author = uname
        },
        methods: {
            // 失去焦点事件
            onEditorBlur(quill) {

                this.$refs.form.validateField("content", (errorMsg) => {
                    this.borderColor = "#dcdfe6";
                    if (errorMsg) {
                    this.borderColor = "#F56C6C";
                    }
                });
                console.log(quill);
            },
            // 内容改变事件
            onEditorChange({ quill, html, text }) {
                this.form.content = html;
                console.log(quill);
                console.log(text);
            },
            //删除附件
            handleFileRemove(res) {
                for(var j = 0; j < this.files.length; j++) {
                    var nam = this.remo[j].data[0].name
                    if(nam === res.name) {
                        this.files = this.files.slice(0, j).concat(this.files.slice(j + 1,  this.files.length));
                    }
                }
            },
            //上传附件
            handleFileSuccess(res){
                if(res.code == 0) {
                    this.remo.push(res);
                    let str = res.data[0]
                    this.files.push(str);
                }
            },
            //预览
            handleSee() {
                this.$refs["form"].validate((valid) => {
                    this.$refs.form.validateField("content", (errorMsg) => {
                    this.borderColor = "#dcdfe6";
                    if (errorMsg) {
                        this.borderColor = "#F56C6C";
                    }
                    });
                    if (valid) {
                    this.dialogTableVisible = true;
                    } else {
                    return false;
                    }
                });
            },
            //获取tags
            getTags() {
                this.axios.get('/intelligence/tags/').then((res) => {
                    if(res.data.code===0){
                        this.tagsList = res.data.data;
                    }

                })
            },
            //获取types
            getTabs() {
                this.axios.get('/intelligence/tabs/').then((res) => {
                    if(res.data.code===0){
                        this.typeList = res.data.data;
                    }

                })
            },
            //上传文章
            postArticle() {
                this.$refs["form"].validate((valid) => {
                    this.$refs.form.validateField("content", (errorMsg) => {
                    this.borderColor = "#dcdfe6";
                    if (errorMsg) {
                        this.borderColor = "#F56C6C";
                    }
                    });
                    if (valid) {
                    this.centerDialogVisible = true;
                    } else {
                    return false;
                    }
                });
                if(this.centerDialogVisible == true) {
                    var tags = this.checkList.join(",");
                    var params ={
                        "title":this.form.title,
                        "author":this.form.author,
                        "type":this.form.type,
                        "tags":tags,
                        "content":this.form.content,
                        "coverPicture":this.url,
                        "summary": this.form.summary,
                        "files": this.files
                    }
                    this.axios({
                        method: 'post',
                        url:'/intelligence/news/',
                        headers: {
                                'Content-Type': 'application/json;charset=UTF-8'
                            },
                        data:params
                    }).then((res)=>{
                        console.log(res);
                    });
                }

            },

            //上传封面
            handleAvatarSuccess(res,) {
                // console.log(res.data[0].url);
                this.form.url = res.data[0].url
                this.url = res.data[0].url
                this.rules.imageUrl[0].required = false;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传封面图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    }
</script>
<style lang="scss" scoped>
    .editor{
        text-align: left;
        margin-left: 135px;
        margin-right: 25px;
        .title{
            text-align: center;
            margin-top: 40px;
            margin-bottom: 40px;
            font-size:25px;
            font-weight: bold;
        }
        .el-form{
            .el-form-item{
                .el-input{
                    width: 50%;
                }
                div{
                    div{
                        .ql-toolbar{
                            line-height: 1rem;
                        }
                        .ql-container{
                            min-height: 20rem!important;
                        }
                    }
                }
                .quill{
                    .ql-toolbar{
                        line-height: 1rem;
                    }
                    .ql-container{
                        min-height: 20rem!important;
                    }
                }
            }
            .btn{
                text-align: center;
                margin: 3rem;
            }
        }
        .el-dialog{
            .addfile{
                margin: 4rem 0;
            }
        }
    }
    .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
